from django.shortcuts import render
from django.views import View
# Create your views here.
from apps.contents.models import GoodsChannel, ContentCategory

class IndexView(View):
    """首页测试视图"""
    def get(self, request):
        categories = {}

        #查询所有的37频道
        # channels = GoodsChannel.objects.all().order_by('group_id', 'sequence')
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')

        for i in  channels:
            #通过频道数据关联的组取出对应的组号
            group_id = i.group.id

            #将group_id作为字段channels的key
                #判断group_id是否已存在categories字典中
            if group_id not in categories:
                categories[group_id] = {'channels': [],
                                      'sub_cats': []}

            #获取当前频道关联的一级分类来获取name
            cat1 = i.category

            #添加每组中的频道数据
            categories[group_id]['channels'].append({
                "id":i.id,
                "name":cat1.name,
                "url":i.url
            })

            #添加组中的二级分类和三级分类
            for cat2 in cat1.subs.all():
                # 使用二级分类查询关联的三级分类
                sub_cats = []
                for cat3 in cat2.subs.all():
                    sub_cats.append({
                        "id": cat3.id,
                        "name": cat3.name,
                    })

                categories[group_id]['sub_cats'].append({
                    "id":cat2.id,   #二级分类id
                    "name":cat2.name,   #二级分类名字
                    "sub_cats":sub_cats   #二级关联的三级分类
                })

        contents = {}
        content_categories = ContentCategory.objects.all()
        for i in content_categories:
            contents[i.key] = i.content_set.filter(status=True).order_by('sequence')

            
        pass